<?php

namespace App\Http\Controllers;

use App\Common\HttpClient;
use App\Common\Logger;
use App\Common\Sql;
use App\Common\Tool;
use App\Exceptions\ApiException;
use App\Logic\RegisterLogic;
use App\Logic\SmsLogic;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class Register extends Base
{

    /**
     * @return string
     * @throws ApiException
     */
    public function logic()
    {
        if (!isset($this->param['user'])) {
            return $this->returnError(1, "手机号参数未输入.");
        } else {
            $user = $this->param['user'];
            if (!preg_match("/^1[34578]\d{9}$/", $user)) {
                return $this->returnError(2, '手机号格式错误');
            }
        }

        if (!isset($this->param['password'])) {
            return $this->returnError(3, "password must be need.");
        }
        $password_reg = '/[a-zA-Z0-9]{4,20}/';
        if (!preg_match($password_reg, $this->param['password'])) {
            return $this->returnError(4, '密码最长为4-20位，包含英文、数字，请重新填写');
        }

        if (!isset($this->param['nick_name'])) {
            return $this->returnError(5, "昵称不能为空");
        } else {
            $nick_name = $this->param['nick_name'];
            $reg       = "/^[0-9a-zA-Z\x{4e00}-\x{9fa5}]+$/u";
            if (preg_match($reg, $nick_name)) {
                $cnt = mb_strwidth($nick_name, "utf-8");
                if ($cnt >= 4 && $cnt <= 14) {
                } else {
                    return $this->returnError(6, "昵称长度2到7个汉字字符,或者4~14个英文数字字符");
                }
            } else {
                return $this->returnError(7, "昵称只支持中文、英文、数字");
            }

        }

        if (!isset($this->param['ua'])) {
            $ua = "";
        } else if (strlen($this->param['ua']) > 20) {
            $ua = substr($this->param['ua'], 0, 20);
        } else {
            $ua = $this->param['ua'];
        }

        if ($this->param['code'] != 9527) {
            //验证短信
            SmsLogic::instance()->checkRegisterSmsCode($this->param['user'], $this->param['code']);
        }

        return $this->returnData(RegisterLogic::instance()->handle([
            'is_check_phone' => 1,
            'phone_num' => $this->param['user'],
            'nick_name' => $this->param['nick_name'],
            'password' => $this->param['password'],
            'ua' => $ua,
            'type' => 1
        ]));
    }

}
